﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using myBoard.App.MagnetStore;
using myBoard.App.Components.MagnetsStore;
using myBoard.Framework;
using System.Text.RegularExpressions;
using System.IO;

namespace myBoard.App
{
	/// <summary>
	/// Interaction logic for NewUserControl.xaml
	/// </summary>
	public partial class NewUserControl : UserControl
	{
        public delegate void OnRegistrationCanceled();
        public delegate void OnRegistrationCompleted(NewUserControl sender);
        public event OnRegistrationCanceled RegistrationCanceled;
        public event OnRegistrationCompleted RegistrationCompleted;

		public NewUserControl()
		{
			this.InitializeComponent();
            _okBt.Click += new RoutedEventHandler(_okBt_Click);
            _cancelBt.Click += new RoutedEventHandler(_cancelBt_Click);
            _openAvatarBt.Click += new RoutedEventHandler(_openAvatarBt_Click);
		}

        void _openAvatarBt_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.OpenFileDialog ofd = new System.Windows.Forms.OpenFileDialog();
            ofd.Title = "Select your avatar";
            ofd.Filter = "PNG files (*.png)|*.png";
            ofd.ShowDialog();
            _avatarFileNameTbx.Text = ofd.FileName;
            _avatarImage.Source = new BitmapImage(new Uri(ofd.FileName));
            _questionMark.Visibility = Visibility.Hidden;
        }

        void _cancelBt_Click(object sender, RoutedEventArgs e)
        {
            if (RegistrationCanceled != null)
                RegistrationCanceled();
        }

        void _okBt_Click(object sender, RoutedEventArgs e)
        {
            if (!IsValidEmail(_userEmailTbx.Text))
            {
                myBoard.Framework.Forms.MessageBox.Show("Wrong Email format",
                    "Something is wrong with the email address you entered.\r\nA valid email address looks like yourname@provider.com.",
                    "Magnets Store", System.Diagnostics.EventLogEntryType.Error);
                return;
            }
            if (_userPasswordTbx.Password != _userPassword2Tbx.Password)
            {
                myBoard.Framework.Forms.MessageBox.Show("Password mismatch",
                    "Something is wrong with the your password, please make sure they are the same.", "Magnets Store",
                     System.Diagnostics.EventLogEntryType.Error);
                return;
            }
            if (string.IsNullOrEmpty(_userNickNameTbx.Text))
            {
                myBoard.Framework.Forms.MessageBox.Show("Empty nickname",
                    "You must specify a nickname for your account.", "Magnets Store",
                     System.Diagnostics.EventLogEntryType.Error);
                return;
            }
            if (string.IsNullOrEmpty(_userPasswordTbx.Password))
            {
                myBoard.Framework.Forms.MessageBox.Show("Empty password",
                    "You must specify a password for your account", "Magnets Store",
                     System.Diagnostics.EventLogEntryType.Error);
                return;
            }
            User user = new User();
            byte[] avatar = null;
            if (!string.IsNullOrEmpty(_avatarFileNameTbx.Text) &&
                File.Exists(_avatarFileNameTbx.Text))
            {
                avatar = Framework.Tools.ConvertFileToByteArray(_avatarFileNameTbx.Text);
            }
            user.Comment = _userAboutYou.Text;
            user.Email = _userEmailTbx.Text;
            user.FirstName = _userFirstNameTbx.Text;
            user.LastName = _userLastNameTbx.Text;
            user.Nickname = _userNickNameTbx.Text;
            user.Password = _userPasswordTbx.Password;
            user.Twitter = _twitterTbx.Text;
            user.Website = _userWebsiteTbx.Text;
            MagnetsStoreClient.Client.RegisterCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(delegate(object s, System.ComponentModel.AsyncCompletedEventArgs args)
                {
                    if (args.Error != null)
                    {
                        ExceptionsManager.LogException("Magnets Store", "Registration failed", args.Error, System.Diagnostics.EventLogEntryType.Error, true);
                    }
                    else
                    {
                        if (RegistrationCompleted!=null)
                        {
                            RegistrationCompleted(this);
                        }
                    }
                });
            MagnetsStoreClient.Client.RegisterAsync(user, avatar);
        }

        void Client_RegisterCompleted()
        {
            
        }

        private bool IsValidEmail(string email)
        {
            string patternStrict = @"^(([^<>()[\]\\.,;:\s@\""]+"
                  + @"(\.[^<>()[\]\\.,;:\s@\""]+)*)|(\"".+\""))@"
                  + @"((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}"
                  + @"\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+"
                  + @"[a-zA-Z]{2,}))$";
            Regex reStrict = new Regex(patternStrict);
            bool isStrictMatch = reStrict.IsMatch(email);
            return isStrictMatch;
        }
	}
}